﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.vCard
{
    /// <summary>CCPSIP_043：回覆 vCard 交換請求 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。
    /// Scanner = vCard請求方(QR Code掃描者)。
    /// ReplyAct = 接受="Y"，拒絕="N"。
    /// 上傳檔案 = vCard 檔案(.vcf)。

    public class vcf_req_reply : IHttpHandler
    {
        private string kVCardRootDir = ChrisKit.RootDir + "CCPSIP\\vCard";//ios.ccp
        // iCloud: Limits for Contacts
        // http://support.apple.com/kb/HT4489
        private const int kFileSizeLimit = 2 * 1048576;//2MB


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];
                string Scanner = req.Form["Scanner"];//vCard請求方(QR Code掃描者)
                bool Accepted = (req.Form["ReplyAct"].ToUpper() == "Y" ? true : false);//接受或拒絕

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                if (Accepted)
                {
                    //【02】取得上傳的檔案
                    //
                    if (req.Files.Count < 1 || req.Files[0].ContentLength < 64)
                    {
                        throw new Exception("Error_02: No upload file");//沒有上傳檔案
                    }
                    else if (req.Files[0].ContentLength > kFileSizeLimit)
                    {
                        throw new Exception("Error_02: File size exceeds limit");//檔案大小超過上限
                    }


                    //【03】儲存 vCard 檔案
                    //
                    string vcfDir = string.Format(@"{0}\{1}", kVCardRootDir, userInfo.SIP_Num);
                    if (!Directory.Exists(vcfDir))
                    {
                        Directory.CreateDirectory(vcfDir);
                    }
                    string vcfPath = string.Format(@"{0}\{1}_{2:yyyyMMdd_HHmmss}.vcf", vcfDir, userInfo.SIP_Num, reqTime);
                    if (!File.Exists(vcfPath))
                    {
                        req.Files[0].SaveAs(vcfPath);
                    }
                }


                //【04】更新 vCard 交換記錄狀態
                //
                OracleKitVCard.ReplyVCardSend(userInfo, Scanner, reqTime, Accepted);


                //【98】通知Push Service
                //
                PushKit.WakePushAsync(PushKit.PushType.Msg);


                //【99】回傳OK
                //
                resultStr = "OK";
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
